package tt.dz.appserver.mvc.interceptor;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import tt.dz.appserver.entity.model.ResultMappingEntity;
import tt.dz.appserver.util.Constants;
import tt.dz.appserver.util.enums.Response;
import tt.dz.appserver.util.resource.ResourceUtils;

/**
 * http签名校验
 * 
 * @author 谢龙飞
 * 
 */
@SuppressWarnings(value={"unused"})
public class HttpSignInterceptor extends ApplicationObjectSupport implements HandlerInterceptor {

	/** 日志信息 */
	private static final Logger LOG = Logger.getLogger("[HTTP 签名,IP 拦截器 ]:  ");

//	private static final int allRequestCount = Integer.valueOf(ResourceUtils.getProperties("cus", "request.count"));
	
	private static final CacheManager manager = CacheManager.create();

	/** 不用拦截 */
	private List<String> excludes;

	public List<String> getExcludes() {
		return excludes;
	}

	public void setExcludes(List<String> excludes) {
		this.excludes = excludes;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception e)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

		// 获取IP地址
		String ipAddr = request.getRemoteAddr();
		LOG.info("IP【 "+ipAddr+" 】访问系统");
//		// 取到ehcache ip配置节点
//		Cache cache = manager.getCache("ip");
//
//		// 获取ip访问时间
//		Element lastTimeElement = cache.get(ipAddr);
//
//		// 当前时间
//		long nowTime = System.currentTimeMillis();
//		// 请求次数
//		int requestCount = 0;
//		
//		//如果最登录时间节点不为空
//		if (lastTimeElement != null) {
//			
//			@SuppressWarnings("unchecked")
//			Map<String, Object> lastTime = (Map<String, Object>) lastTimeElement.getObjectValue();
//			//获取最后登录时间
//			Object otime = lastTime.get("time");
//			long time = Long.valueOf(otime.toString());
//
//			//获取请求次数
//			requestCount = (int) lastTime.get("requestCount");
//			
//			LOG.info("IP【 "+ipAddr+" 】上次访问时间为【 "+time+" 】,当前时间为【 "+nowTime+" 】"+requestCount);
//			
//			//如果请求间隔小于0.1分钟并且请求次数大于10
//			if (((nowTime - time) < 1 * 1000) && requestCount >= allRequestCount) {
//
//				//抛出异常信息
//				LOG.error("此IP【 "+ipAddr+" 】在一秒钟之内访问了【"+requestCount+"】次, 访问出现异常,连续访问次数超过限制,拒绝操作");
//				
//				ServletOutputStream out = null;
//				try {
//					response.setContentType("application/json;charset=utf-8");
//					out = response.getOutputStream();
//					out.print("error");
//				} catch (Exception e) {
//					e.printStackTrace();
//				} finally {
//					if (out != null) {
//						out.flush();
//						out.close();
//					}
//				}
//				return false;
//			}
//		}
//		Map<String, Object> requestMap = new HashMap<String, Object>();
//		requestMap.put("time", nowTime);
//		requestMap.put("requestCount", (requestCount+1));
//		Element element = new Element(ipAddr, requestMap);
//		cache.put(element);
//
//		// 是否不用拦截
//		String uri = request.getRequestURI();
//		LOG.debug("请求地址是：" + uri);
//		for (String exclude : excludes) {
//			if (uri.contains(exclude)) {
//				LOG.debug("无需拦截：" + uri);
//				return true;
//			}
//		}
//
//		// 获取所有参数
//		Map<String, String[]> paramsMap = request.getParameterMap();
//		// 如果无任何参数的话
//		if (paramsMap == null || paramsMap.size() <= 0) {
//			LOG.info("无参数的接口访问");
//			return true;
//		}
//		// 排序序map
//		TreeMap<String, String[]> sortMap = new TreeMap<String, String[]>(paramsMap);
//
//		// 遍历Map
//		Set<String> keys = sortMap.keySet();
//		StringBuffer valueBuffer = new StringBuffer();
//
//		LOG.info("参数顺序是：");
//		for (String key : keys) {
//			LOG.info(key);
//			// 排除sign token等参数
//			if (!"".equals(key) && !"sign".equals(key) && !"token".equals(key)) {
//				String[] valueArray = sortMap.get(key);
//				// 连接接所有参数的值
//				valueBuffer.append(valueArray);
//			}
//		}
//		if (1 + 1 >= 2) {
//			return true;
//		}
//		// 连接参数校验md5 盐
//		valueBuffer.append(Constants.Key.PARAM_SIGN_KEY);
//		// 加密字符串
//		String hashSign = DigestUtils.md5Hex(valueBuffer.toString().getBytes("UTF-8"));
//		// 获取用户传过来的sign
//		String[] signs = sortMap.get("sign");
//		// 判断是否跟加密结果一致
//		if (signs != null && signs[0].equalsIgnoreCase(hashSign)) {
//			LOG.info("接口校验验通过，允许访问资源");
//			return true;
//		} else {
//			PrintWriter out = null;
//			try {
//				response.setContentType("application/json;charset=utf-8");
//				out = response.getWriter();
//
//				// 403:资源无权限访问 提示签名错误 data为空
//				out.print(JSON.toJSONString(new ResultMappingEntity(Response.NO_PERMISSION.getCode(),
//						Response.NO_PERMISSION.getMsg(), null)));
//			} catch (Exception e) {
//				e.printStackTrace();
//			} finally {
//				if (out != null) {
//					// 关闭流 必须
//					out.close();
//				}
//			}
//		}
		return true;
	}
	public static void main(String[] args) throws InterruptedException {
		long start = System.currentTimeMillis();
		Thread.sleep(3000);
		System.out.println(System.currentTimeMillis()-start);
	}
}
